import java.util.Stack;

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        Stack<ListNode> s = new Stack<>();
        ListNode ret = new ListNode();
        ret.next = head;
        ListNode pre = ret;
        ListNode cur = head;
        while (cur != null) {
            int count = 0;
            while (count < k) {
                count++;
                s.push(cur);
                cur = cur.next;
                if (cur == null) {
                    break;
                }
            }
            // cur = cur.next;
            if (count == k) {
                while (!s.isEmpty()) {
                    ListNode node = s.pop();
                    pre.next = node;
                    pre = node;
                }
            } else if (cur == null) {
                return ret.next;
            }
            pre.next = cur;
        }
        return ret.next;
    }
}
